package edu.gdkm.interceptor;

import edu.gdkm.annotation.LoginInterceptor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SecondInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("----------------------------");
        System.out.println("second interceptor preHandle");
        System.out.println(handler);
        System.out.println("----------------------------");
           if(handler instanceof HandlerMethod){
               HandlerMethod handlerMethod = (HandlerMethod) handler;
               if(!handlerMethod.getMethod().isAnnotationPresent(LoginInterceptor.class)){
                   System.out.println("无需拦截");
                   return true;
               }else{
                   if(null!=request.getSession().getAttribute("user")){
                       return true;
                   }else{
                       request.setAttribute("msg","你没有权限，请登录后再试!");
                       request.getRequestDispatcher("/login.jsp").forward(request,response);
                       return false;
                   }
               }
           }else{
               System.out.println("无需拦截");
               return true;
           }
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("----------------------------");
        System.out.println("second interceptor postHandle");
        System.out.println(modelAndView);
        System.out.println("----------------------------");
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("----------------------------");
        System.out.println("second interceptor afterCompletion");
        System.out.println(ex);
        if(ex!=null){
            request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,response);
        }
        System.out.println("----------------------------");
    }
}